import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { urlConfig } from '@/config'

function useStompClient (messageHandlerFun,connectdHandler,disConnectedHandler){
    let stompClient = null ;
    let sockJs = null;
    const connectCallback = () =>{
        connectdHandler();
        stompClient.subscribe(urlConfig.WS_MONITOR_CHAT_TOPIC, messageHandlerFun,{
            token:"kltoen"
        });
    }
    const errorCalllback = () => {
        disConnectedHandler();
        // 断开自动重连
        setTimeout(init(),2000);
    }
    const connectWs = () =>{
        stompClient.heartbeat.incoming = 0;
        stompClient.heartbeat.outgoing = 1000;
        stompClient.connect({token:"kl"}, connectCallback,errorCalllback);
    }
    const init = () =>{
        sockJs = new SockJS(urlConfig.URL_WS);
        stompClient = Stomp.over(sockJs);
        connectWs();
    }
    init();
    return stompClient;
}
export default useStompClient;
